package com.java.json;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.java.pojo.Person;
import com.java.pojo.PersonListType;
import com.java.pojo.PersonMapType;
import com.sun.org.apache.bcel.internal.generic.GOTO;
import org.junit.Test;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author YAO
 * @create 2021-05-15 20:31
 */
public class JsonTest {

    /**
     * javaBean和json的转换
     */
    @Test
    public void test1(){
        Person person = new Person(1, "姚大帅哥");
        //创建gson对象实例
        Gson gson = new Gson();
        //toJson方法可以把java对象转为json字符串
        String personJsonStr = gson.toJson(person, Person.class);
        System.out.println(personJsonStr);
        //fromJson(json字符串,转换回去的java对象类型)把json字符串转换为java对象
        Person personFromJson = gson.fromJson(personJsonStr, Person.class);
        System.out.println(personFromJson);
    }

    /**
     * list和json的互转
     */
    @Test
    public void test2(){
        ArrayList<Person> list = new ArrayList<>();
        list.add(new Person(1,"姚桑"));
        list.add(new Person(2,"康师傅"));
        list.add(new Person(3,"国哥"));

        Gson gson = new Gson();
        //把list集合转化为json字符串
        String listToJson = gson.toJson(list);
        System.out.println(listToJson);

        List<Person> listFromJson = gson.fromJson(listToJson, new PersonListType().getType());
        System.out.println(listFromJson);
        Person person = listFromJson.get(0);
        System.out.println(person);
    }

    /**
     * map和json的互转
     */
    @Test
    public void test3(){
        HashMap<Integer, Person> map = new HashMap<>();
        map.put(1, new Person(1,"姚桑"));
        map.put(2, new Person(2,"康师傅"));
        map.put(3, new Person(3,"国哥"));

        Gson gson = new Gson();
        String mapJsonStr = gson.toJson(map);
        System.out.println(mapJsonStr);
//        HashMap<Integer, Person> mapFromJson = gson.fromJson(mapJsonStr, new PersonMapType().getType());
        //直接传入一个匿名内部类的实例的getType()方法返回的内容
        HashMap<Integer, Person> mapFromJson = gson.fromJson(mapJsonStr, new TypeToken<HashMap<Integer, Person>>(){}.getType());
        System.out.println(mapFromJson);
        System.out.println(mapFromJson.get(1));
    }
}
